package com.itcast.plane.modoule.wx.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itcast.plane.common.HttpClientUtil;
import com.itcast.plane.modoule.user.domain.User;
import com.itcast.plane.modoule.user.mapper.UserMapper;
import com.itcast.plane.modoule.wx.dto.WxLoginDTO;
import com.itcast.plane.modoule.wx.dto.WxPhoneDTO;
import com.itcast.plane.util.JsonResult;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

@Service
public class WxService {

    @Resource
    private HttpClientUtil httpClientUtil;

    @Resource
    private UserMapper userMapper;

    public JsonResult wxLogin(WxLoginDTO loginDTO) {
        String openId = httpClientUtil.doGet(loginDTO.getCode());
        if ("false".equals(openId)){
            return new JsonResult(false,"微信登陆失败请重试");
        }
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        User user = userMapper.selectOne(lambdaQueryWrapper.eq(User::getOpenId,openId));
        if (ObjectUtils.isEmpty(user)){
            return new JsonResult(true,"请输入手机号",openId);
        }else {
            return new JsonResult(true,"登陆成功",user.getId());
        }
    }

    public JsonResult phone(WxPhoneDTO phoneDTO) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone,phoneDTO.getPhone());
        User user = userMapper.selectOne(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(user)){
            user = new User();
            user.setPhone(Long.parseLong(phoneDTO.getPhone()));
            user.setOpenId(phoneDTO.getOpenid());
            userMapper.insert(user);
        }
        return new JsonResult(true,user.getId());
    }
}
